﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using MyFirstSolution.Common;

namespace MyFirstSolution.Model
{
    /// <summary>
    /// 用户帐户实体类
    /// </summary>
    public class User
    {
        /*用户类别等数据应该在用户实体类内部定义--局部化原则*/
        /// <summary>
        /// 管理员用户
        /// </summary>
        public const int Administrator = 1;
        /// <summary>
        /// 普通用户
        /// </summary>
        public const int NormalUser = 2;

        /// <summary>
        /// 默认登录密码
        /// </summary>
        private string DefaultPassword = "123";

        private int id;
        /// <summary>
        /// 用户ID--唯一标识用户，对应数据库中的自增字段
        /// </summary>
        public int ID
        {
            get { return id; } //用户ID对外只读，不能修改
        }

        private string account;
        /// <summary>
        /// 用户登录的帐号
        /// </summary>
        public string Account
        {
            get { return account; }
            set
            {
                account = value.Trim();
            }
        }

        private string password;
        /// <summary>
        /// 用户登录的密码
        /// </summary>
        public string Password
        {
            get { return CodeProcess.DecodeBase64(password); } //读取时解密
            set //保存密码
            {
                password = CodeProcess.EncodeBase64(value); //Base64格式存储
            }
        }

        private int usertype;
        /// <summary>
        /// 用户类型--User.XXX
        /// </summary>
        public int UserType
        {
            get { return usertype; }
            set
            {
                usertype = value;
            }
        }

        /// <summary>
        /// 根据数据集中的一行数据构造用户数据对象
        /// </summary>
        /// <param name="r">数据集中的一行数据</param>
        public User(System.Data.DataRow r)
        {
            id = Convert.ToInt32(r["ID"].ToString());
            account = r["Account"].ToString().Trim();
            string s = r["Password"].ToString().Trim();
            if (s.Length > 0)
                password = s;
            else
                Password = DefaultPassword; //不允许空密码，密码为空时设置为默认密码
            UserType = Convert.ToInt32(r["UserType"].ToString());
        }

        //一般类都应该有的一个操作--〉将当前对象用一个字符串表示出来
        public override string ToString()
        {
            return Account;
        }

        public User(string account, string password, int usertype)
        {
            this.account = account;
            this.password = CodeProcess.EncodeBase64(password);
            this.UserType = usertype;
        }
    }
}
